<template>
  <div class="student-manage">
    <p class="title">
      学生管理<label class="label">{{ total }}</label>
    </p>
    <div class="setting">
      <p class="pwd">
        <span><span class="tip">默认密码：</span>a123456</span
        ><el-divider direction="vertical" />
        <span class="reset" @click="handleResetPwd">重置密码</span>
      </p>
      <div class="btn-box">
        <button
          v-if="selectedList.length"
          class="btn text-btn"
          @click="cancelSelect"
        >
          取消选择
        </button>
        <button class="btn create-btn" @click="createTarget">
          创建靶向班（{{ selectedList.length }}）
        </button>
        <button v-if="!isTarget" class="btn export-btn">
          <a :href="getDownloadUrl"
            ><img
              src="@/assets/images/class-manage/export-icon.svg?url"
            />导出</a
          >
        </button>
      </div>
    </div>
    <el-table
      ref="tableRef"
      class="table"
      :data="getList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="100" align="center" />
      <el-table-column prop="username" label="用户姓名" align="center">
        <!-- <template #default="scope">
          {{ scope.row.username || scope.row.student_name }}
        </template> -->
      </el-table-column>
      <el-table-column
        prop="account"
        label="账号"
        align="center"
      ></el-table-column>
      <el-table-column prop="gender_name" label="性别" align="center">
        <template #default="scope">
          <span>{{ scope.row.gender_name || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="student_code" label="学籍号" align="center">
        <template #default="scope">
          <span>{{ scope.row?.student_code || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="student_id_code" label="学号" align="center">
      </el-table-column>
      <el-table-column prop="class" label="所属班级" align="center"
        ><template #default="scope">
          <span>{{ scope.row.grade_name }}{{ scope.row.class_name }}</span>
        </template></el-table-column
      >
    </el-table>
    <el-dialog
      class="reset-pwd-dialog"
      v-model="resetVisible"
      width="300"
      title="重置密码"
    >
      <div class="selected-stu">
        <p>已选择学生：</p>
        <p class="stu-wrapper">
          <label v-for="(item, index) in selectedList" :key="item.student_id"
            >{{ item.username
            }}<el-icon class="remove-icon" @click="removeStudent(index)">
              <Close /> </el-icon
          ></label>
        </p>
      </div>
      <el-form ref="formRef" :model="resetForm" :rules="rules">
        <el-form-item label="自定义密码：" prop="pwd" required>
          <el-select v-model="resetForm.pwd" placeholder="请输入密码">
            <el-option
              v-for="item in pwdEnum"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item
          v-if="resetForm.pwd === pwdEnum.Custom"
          label="密码："
          prop="define"
          required
        >
          <el-input v-model="resetForm.define" />
        </el-form-item>
      </el-form>
      <p class="btn-box">
        <button class="btn cancel" @click="cancelResetPwd">取消</button>
        <button class="btn confirm" @click="confirmResetPwd">确认</button>
      </p>
    </el-dialog>
    <create-target-class
      :visible="createVisible"
      :studentList="getSelectedTarget"
      :currentGrade="props.currentClass?.grade_id"
      :schoolId="String(authStore.userInfo.school_id)"
      :teacherId="authStore.userInfo.userId"
      @close="handleClose"
    ></create-target-class>
  </div>
</template>
<script setup>
import CreateTargetClass from './CreateTargetClass.vue'
import { useAuthStore } from '@/stores'
import { ACCOUNT_CENTER_SYSTEM } from '@/apis/host.js'
import { resetPwd } from '@/apis/class-manage/index.js'
import { Close } from '@element-plus/icons-vue'
import { ref, computed, reactive } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'

const authStore = useAuthStore()
const route = useRoute()

const props = defineProps({
  studentList: {
    type: Array,
    default: () => []
  },
  total: {
    type: Number,
    default: 0
  },
  currentClass: {
    type: Object,
    default: () => {}
  }
})

const getList = computed(() => {
  const res = props.studentList.map(item => {
    return {
      ...item.school_class_info,
      ...item.student_info
    }
  })
  return res
})

const selectedList = ref([])
const handleSelectionChange = val => {
  selectedList.value = val
}

// 创建靶向班
const tableRef = ref()
const createVisible = ref(false)
const createTarget = () => {
  if (!selectedList.value.length) {
    ElMessage.warning('请先选择学生！')
    return
  }
  createVisible.value = true
}

const getSelectedTarget = computed(() => {
  return selectedList.value.map(item => {
    return {
      studentName: item.username,
      key: item.student_id
    }
  })
})

const cancelSelect = () => {
  selectedList.value = []
  tableRef.value.clearSelection()
}

const handleClose = () => {
  createVisible.value = false
  cancelSelect()
}

// 重置密码
const pwdEnum = {
  Default: 'a123456',
  Custom: '自定义',
  BehindSix: '账号后6位'
}
const resetForm = reactive({
  pwd: '',
  define: ''
})
const resetVisible = ref(false)
const handleResetPwd = () => {
  if (!selectedList.value.length) {
    ElMessage.warning('请先选择学生')
    return
  }
  resetVisible.value = true
}

const removeStudent = index => {
  selectedList.value.splice(index, 1)
}

const formRef = ref()
const rules = reactive({
  pwd: [{ required: true, message: '请输入密码', trigger: 'change' }],
  define: [
    {
      required: true,
      message: '请输入自定义密码',
      trigger: 'blur'
    }
  ]
})

const confirmResetPwd = async () => {
  if (!selectedList.value.length) {
    ElMessage.warning('请先选择学生！')
    return
  }
  if (!formRef.value) return
  await formRef.value.validate(async valid => {
    if (valid) {
      const list = []
      for (let index = 0; index < selectedList.value.length; index++) {
        const element = selectedList.value[index]
        if (resetForm.pwd === pwdEnum.BehindSix) {
          if (!element.account) {
            ElMessage.error('账号为空！')
            return
          } else {
            list.push({
              person_id: Number(element.student_id),
              new_password: element.account.substr(-6)
            })
          }
        } else {
          list.push({
            person_id: Number(element.student_id),
            new_password:
              resetForm.pwd === pwdEnum.Default
                ? pwdEnum.Default
                : resetForm.define
          })
        }
      }
      await resetPwd({
        person_password_list: list
      })
      cancelResetPwd()
      ElMessage.success('密码重置成功！')
    }
  })
}

const cancelResetPwd = () => {
  formRef.value?.resetFields()
  resetVisible.value = false
}

const isTarget = computed(() => route.path.indexOf('target') > -1)

const getDownloadUrl = computed(() => {
  return `${ACCOUNT_CENTER_SYSTEM}/api/v2/person/student/export?page=1&page_size=100&school_id=${authStore.userInfo.school_id}&grade_id=${props.currentClass?.grade_id}&class_id=${props.currentClass?.id}`
})
</script>
<style lang="less" scoped>
.student-manage {
  .title {
    display: flex;
    align-items: center;
    gap: 8px;
    position: relative;
    padding-left: 20px;
    color: rgba(4, 11, 26, 0.9);
    font-size: 18px;
    font-weight: 700;
    margin-bottom: 16px;

    &::before {
      position: absolute;
      content: '';
      top: 50%;
      transform: translateY(-50%);
      background-color: @color-brand-regular;
      width: 7px;
      height: 21px;
      left: 0;
    }

    .label {
      display: inline-block;
      color: @color-brand-regular;
      background-color: #e9eeff;
      width: 24px;
      height: 24px;
      border-radius: 13px;
      font-size: 12px;
      font-weight: 500;
      line-height: 24px;
      text-align: center;
    }
  }

  .setting {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 12px;

    .pwd {
      display: flex;
      align-items: center;
      gap: 10px;

      .tip {
        color: #9b9da3;
      }

      .el-divider {
        background: #040b1a80;
        width: 1.5px;
      }

      .reset {
        color: #ff6d65;
        cursor: pointer;
      }
    }

    .btn-box {
      display: flex;
      align-items: center;

      .btn {
        padding: 7px 17px;
        border: 1px solid @color-brand-regular;
        border-radius: 5px;
        background-color: unset;
        cursor: pointer;
        font-weight: 500;
        margin-left: 20px;
        display: inline-flex;
        align-items: center;
        font-size: 16px;

        img {
          width: 17px;
          height: 18px;
          margin-right: 10px;
        }
      }

      .text-btn {
        border: unset;
        color: @color-brand-regular;
      }

      .create-btn {
        background-color: @color-brand-regular;
        color: #fff;
      }

      .export-btn {
        color: @color-brand-regular;

        a {
          text-decoration: unset;
          color: @color-brand-regular;
          display: inline-flex;
          align-items: center;
        }
      }
    }
  }

  :deep(.el-table) {
    thead {
      background-color: #f2f4f9;
      tr {
        background-color: #f2f4f9;
        color: #040b1af2;

        font-size: 16px;
        border-radius: 14px 0;

        th {
          padding: 17px 0;

          &:first-child {
            border-radius: 15px 0 0 0;
          }

          &:last-child {
            border-radius: 0 15px 0 0;
          }

          &:not(:last-child):after {
            content: '';
            position: absolute;
            right: 0;
            top: 50%;
            transform: translateY(-50%);
            height: 16px;
            width: 1px;
            background: #1c2230;
          }
        }

        .el-table__cell {
          border-bottom: unset;

          .cell {
            font-weight: 500;
          }
        }
      }
    }

    &__cell {
      background-color: unset;
      padding: 10px 0;
    }
  }

  :deep(.reset-pwd-dialog) {
    width: 600px;

    .el-dialog__header {
      color: #040b1a;
      font-size: 24px;
      font-weight: 700;
    }

    .tip {
      font-size: 18px;
      font-weight: 500;
      margin-bottom: 20px;
    }

    .selected-stu {
      display: flex;
      margin-bottom: 20px;

      p {
        width: 126px;
        color: #040b1ab2;
        font-size: 18px;
        text-align: right;
      }

      .stu-wrapper {
        flex: 1;
        display: flex;
        gap: 10px;
        flex-wrap: wrap;

        label {
          display: inline-flex;
          align-items: center;
          border: 1px solid #9bc3ff;
          color: #9bc3ff;
          padding: 4px 10px;
          border-radius: 3px;
          gap: 20px;
          font-size: 14px;
          font-weight: 500;

          .close-icon {
            cursor: pointer;
          }
        }
      }
    }

    .btn-box {
      text-align: center;

      .btn {
        margin-left: 20px;
        background-color: #fff;
        border: 1px solid @color-brand-regular;
        border-radius: 3px;
        font-size: 16px;
        font-weight: 700;
        padding: 7px 20px;
      }

      .confirm {
        background-color: @color-brand-regular;
        color: #fff;
      }

      .cancel {
        color: @color-brand-regular;

        &:hover {
          background-color: #ecf5ff;
        }
      }
    }
  }

  :deep(.el-form) {
    margin-bottom: 20px;

    .el-form-item {
      &__label {
        font-size: 18px;
        width: 126px;
        text-align: left;
        padding: unset;
      }
    }

    .el-input {
      width: 240px;
      height: 36px;
    }

    .el-select {
      width: 240px;

      &__wrapper {
        height: 36px;
        font-size: 14px;
        color: #9bc3ff;
      }
    }
  }
}
</style>
